<template>
  <div class="tenantMenu_main main_container user_container">
    <div v-loading="loading" class="main_main">
      <div class="main_main_container">
        <div class="main_main_left">
          <div class="title">采购申请单</div>
          <div class="main_main_left_top">
            <el-tree
              :data="typeList"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :highlight-current="true"
              :props="defaultProps"
              @node-click="getMaterialInfo"
            />
          </div>
        </div>
        <div class="main_main_right">
          <div class="SearchBar_main main_main_search">
            <div class="main_main_search_item">
              <el-input v-model="pageData.searchValue" class="search_input" placeholder="请输入物料编码或名称" clearable @keyup.enter.native="()=>{pageData.pageNum=1; getList()}" @clear="getList" />
              <el-button class="button_icon" icon="el-icon-search" @click.stop="()=>{pageData.pageNum=1; getList()}" />
            </div>
          </div>
          <div ref="table_container" style="margin-top:20px" class="table_container">
            <el-table
              ref="table"
              :data="tableData"
              stripe
              border
              :height="tableHeight"
              style="width: 99.9%"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              :row-class-name="rowClassName"
              :header-cell-class-name="headerCellClassName"
              @row-click="rowClick"
              @sort-change="
                (column) => {
                  sortChange(column, this);
                }
              "
              @selection-change="
                (val) => {
                  selectionChange(val, this);
                }
              "
            >
              <el-table-column type="selection" width="70" align="center" :selectable="tableSelectable" />
              <Column
                v-for="(column, index) in defaultTableColumns"
                :key="index"
                :prop="column.prop"
                :is-show="column.isShow"
                :label="column.label"
                :sortable="column.sortable"
                :min-width="column.minWidth"
                :width="column.width"
              />
              <el-table-column
                label="附件"
                min-width="80"
              >
                <template slot-scope="scope">
                  <FileManage
                    :file-names="scope.row.fileName"
                    :file-real-names="scope.row.fileRealName"
                    :file-urls="scope.row.fileUrl"
                    :readonly="true"
                    class="accessory"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="purchase"
                label="采购数量"
                fixed="right"
                min-width="200"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.purchase" :disabled="scope.row.isStatus" clearable placeholder="请输入" @input="changeTaxPrice($event,scope.row,scope.$index)" />
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="main_bottom">
            <pagination
              :total="total"
              :page.sync="pageData.pageNum"
              :limit.sync="pageData.pageSize"
              :selected-num="selectionsAll.length"
              @pagination="getList"
            />
          </div>
        </div>
      </div>
    </div>
    <div style="background:white;border-top:1px solid rgba(51, 51, 51, 0.5)" class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { orderDetailList, orderList } from '@/api/purchaseManage/purchaseOrder'
import AddOrUpdate from '../purchaseApply/addOrUpdate' // 新增或编辑页面

export default {
  props: {
    layerid: {},
    id: {},
    copyData: {},
    selectedRow: {}
  },
  data() {
    return {
      materialTypeId: '',
      typeList: [],
      activeNum: 1,
      deptData: [],
      currentDeptId: '',
      currentDeptName: '',
      loading: false,
      pageId: '用户管理', // 页面唯一标识
      typeId: '',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc',
        searchValue: ''
      },
      total: 1, // 数据一共有多少条
      mainId: 'purchaseRequisitionDetailIds', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      peopleList: [],
      defaultTableColumns: [
        // 表格常规字段（初始值）
        { prop: 'purchaseRequisitionCode', label: '采购申请单', minWidth: '140' },
        { prop: 'materialCode', label: '物料编码', minWidth: '140' },
        { prop: 'materialName', label: '物料名称', minWidth: '140' },
        { prop: 'materialModel', label: '规格型号', minWidth: '100' },
        { prop: 'materialUnitLabel', label: '物料单位', minWidth: '100' },
        { prop: 'stockNum', label: '库存数量', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'requireNumber', label: '需求数量', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'applicationNumber', label: '申请数量', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'transitNumber', label: '在途数量', minWidth: this.SETTINGS.settings_decimalDigits_length },
        { prop: 'requireTime', label: '需求日期', minWidth: '140' },
        { prop: 'remark', label: '备注', minWidth: '200' }
      ],

      operationData: [
        // 右上角的操作按钮
        { label: '导入', perm: 'system:user:import' },
        { label: '新增', perm: 'system:user:add' },
        { label: '批量删除', perm: 'system:user:delete' },
        { label: '批量导出', perm: 'system:user:export' },
        { label: '页面配置', perm: '' }
      ],
      defaultProps: {
        label: 'code',
        children: 'children'
      }
    }
  },
  mounted() {
    this.getList()
    this.getMaterialTypeList()
    this.selectionsAll = this.selectedRow
    this.$nextTick(() => {
      this.tableHeight = this.$refs.table_container.offsetHeight
    })
  },
  methods: {
    tableSelectable(row, index) {
      if (row.isStatus) {
        return false
      } else {
        return true
      }
    },
    rowClick(row, column) {
      if ((!column) || (column && (column.property === 'purchase')) || row.isStatus) {
      } else {
        this.$refs.table.toggleRowSelection(row)
      }
    },
    headerCellClassName(data) {
      if (['purchase'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    rowClassName({ row, rowIndex }) {
      if (this.selectionsAll.length > 0 && ((this.selectionsAll.some(item => item.purchaseRequisitionDetailIds == row.purchaseRequisitionDetailIds)))) {
        return 'rowSelected'
      }
    },
    getMaterialTypeList() {
      orderDetailList(this.pageData).then(res => {
        this.typeList.push({ code: '全部', id: '0', children: [] })
        this.typeList[0].children = res.data
      })
    },
    getList() {
      if (this.materialTypeId == '0' || this.materialTypeId == '') {
        this.materialTypeId = null
      }
      orderList({ ...this.pageData, id: this.materialTypeId }).then(res => {
        console.log(this.selectionsAll, 'this.selectionsAll')
        const tableDataOne = this.$deepClone(res.data)

        tableDataOne.forEach(item => {
          item.purchase = ''
          item.purchaseRequisitionDetailIds = item.id
        })

        this.total = res.total
        if (this.selectionsAll && this.selectionsAll.length > 0) {
          this.selectionsAll.forEach(item => {
            tableDataOne.forEach(item2 => {
              if (item.purchaseRequisitionDetailIds == item2.purchaseRequisitionDetailIds) {
                item2.purchase = item.purchase
              }
            })
          })
        }
        this.tableData = tableDataOne
        const arr = []
        this.copyData.filter(item => { // 筛选出被关闭的数据， 不可选中
          if (item.status == '3') {
            arr.push(item.purchaseRequisitionDetailIds)
          }
        })
        const arr1 = arr.toString()
        const arr2 = arr1.split(',') // 后端返的字符串， 需要处理成数组
        arr2.filter(item => { // 遍历 匹配id相同的 不让输入
          this.tableData.filter(ele => {
            if (item == ele.id) {
              ele.isStatus = true
            }
          })
        })
        arr2.filter(item => { // 遍历 匹配id相同的 要传到编辑页面
          this.selectionsAll.filter(ele => {
            if (item == ele.id) {
              ele.isStatus = true
            }
          })
        })
        // this.selectionsAll = this.selectedRow.filter((item) => // 遍历 匹配id相同的 不让选中
        //   !arr2.some((ele) => ele == item.id)
        // )
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
        })
      })
    },
    getMaterialInfo(item) {
      this.materialTypeId = item.id
      if (this.materialTypeId == '0') {
        this.getRequestList()
      } else {
        this.getOrderGetInfo()
      }
    },
    getOrderGetInfo() {
      this.getList()
    },
    getRequestList() {
      this.getList()
    },
    add() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {} // props
        },
        area: ['880px', '700px'],
        title: '新增采购申请单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    cancel() {
      this.$layer.close(this.layerid)
    },
    changeTaxPrice(e, row, index) {
      this.tableData[index].purchase = e
      this.selectionsAll.forEach(item => {
        if (item.purchaseRequisitionDetailIds == row.purchaseRequisitionDetailIds) {
          item.purchase = e
        }
      })
    },
    onSubmit() {
      if (this.selectionsAll && this.selectionsAll.length <= 0) {
        this.$message.warning('请勾选订单明细')
        return
      }
      if (this.selectionsAll && this.selectionsAll.filter(item => !item.purchase).length > 0) {
        this.$message.warning('采购数量不能为空')
        return
      } else if (this.selectionsAll && this.selectionsAll.filter(item => !this.SETTINGS.reg_no_zero.test(item.purchase)).length > 0) {
        this.$message.warning('采购数量未正确填写')
        return
      }
      this.$parent.showMaterial(this.selectionsAll, this.copyData)
      this.$layer.close(this.layerid)
    }
  }
}
</script>

<style lang="less" scoped>
.main_main {
  height: calc(100% - 50px);
}
.main_main_container {
  width: 100%;
  height: 100%;
  display: flex;

  .main_main_left {
    width: 250px;
    height: calc(100% - 20px);
    padding-right: 20px;
    .title {
      padding: 10px 0;
      border-bottom: 1px solid #387BFC;
      margin-bottom: 10px;
    }
    .main_main_left_top {
      width: 100%;
      height: calc(100% - 80px);
      overflow-y: auto;
      .el-tree {
        background-color: transparent;
      }
      /deep/ .el-tree-node__content:hover {
        background-color: rgba(56, 123, 252, 0.5) !important;
        color: white;
      }
    }
    .main_main_left_bottom {
      width: 100%;
      .main_main_left_bottom_item {
        background-color: rgba(74, 77, 82, 0.2);
        height: 40px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-left: 24px;
      }
      .main_main_left_bottom_item:last-child {
        border-top: 1px solid white;
      }
      .main_main_left_bottom_item:hover {
        background-color: rgba(56, 123, 252, 0.5);
        color: white;
      }
      .active {
        .main_main_left_bottom_item {
          background-color: rgba(56, 123, 252, 1);
          color: white;
        }
      }
    }
  }
  .main_main_right {
    width: calc(100% - 250px);
    height: 100%;
    display: flex;
    flex-direction: column;
    border-left: 1px solid #ECECEC;

    content: "*";
    color: #ff4949;
    margin-right: 2px;
  }
}
.button{
  width: 100px;
  height: 30px;
  color: #fff;
  background-color: #387bfc;
  border-radius: 4px;
  text-align: center;
  line-height: 30px;
}
.formItem_header{
  justify-content: flex-start !important;
  align-items: flex-start !important;
  height: 40px !important;
}
.formItem_header_operate_items{
  height: 30px;
  display: flex;justify-content: center;align-items: center;
  padding: 0px 10px;font-size: 16px;border-radius: 4px;
  color: rgba(56, 123, 252, 1);background-color: rgba(235, 242, 255, 1);
  .item_name{
    font-size: 14px;padding-left: 10px;
  }
}
.formItem_header_operate_items:hover{
  background-color: rgba(235, 242, 255, 0.5);
}
.table_container{
  margin-top: 20px !important;
}
.addtype-main_bottoms{
  padding-right: 20px !important;
  margin: 10px 0;
}
.main_search_item{
  padding-right: 20px !important;
}
.main_main_search{
  padding-right: 20px !important;
}
.main_main_search_item{
  padding-left: 0px !important;
}
.main_main{
  margin-right:0 !important;
  padding-top:0 !important;
}
.button_icon{
  background:#387bfc;
  width:30px;
}
.search_input{
  width:200px;
  margin-right:10px
}
/deep/ .el-input__inner {
  text-align: left !important;
}
.formItem_header {
  padding-left: 20px;
}
/**
 * 解决el-input设置类型为number时，中文输入法光标上移问题
 **/
/deep/.el-input__inner{
  line-height: 1px !important;
}

/**
 * 解决el-input设置类型为number时，去掉输入框后面上下箭头
 **/
/deep/ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.accessory {
  color: #387bfc
}
</style>
